package main

import (
    "os"
    "fmt"
    "time"
    "runtime"
)

var ostype = runtime.GOOS


type DataFile struct {
	fp string
	fd *os.File
}

func (lf *DataFile) Write(p []byte) (int, error) {
    n, err := lf.fd.Write(p)
    if err != nil {
    	fmt.Println("write log file failed", err)
        return -1, err
    }
    return n, err
}

func (lf *DataFile) Open() (int, error) {
	var path string
	if ostype == "windows"{
   		path = fmt.Sprintf(".\\mp3files\\%04d%02d%02d", time.Now().Year(), int(time.Now().Month()), time.Now().Day()) 
	}else if ostype == "linux"{
	    path = fmt.Sprintf("./mp3files/%04d%02d%02d", time.Now().Year(), int(time.Now().Month()), time.Now().Day()) 
	}

	fmt.Println("path", path)
	err := os.MkdirAll(path , 0644)
	os.Chmod(path, 0644)
	if err != nil {
		fmt.Printf("creat dir faild %s", err)
		return -1, err
	} 

	if ostype == "windows"{
   		lf.fp = path + fmt.Sprintf("\\%02d%02d%02d.mp3", time.Now().Hour(), time.Now().Minute(), time.Now().Second())
	}else if ostype == "linux"{
	   lf.fp = path + fmt.Sprintf("/%02d%02d%02d.mp3", time.Now().Hour(), time.Now().Minute(), time.Now().Second())
	}
	
	fmt.Println("path", lf.fp)
	os.Chmod(lf.fp, 0644)
	lf.fd, err = os.OpenFile(lf.fp, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
	//fmt.Println(lf.fd)
	if err != nil {
		fmt.Println("open log file failed", err)
    	return -1, err
	}
	return 0, err
}

func (lf *DataFile) Close() () {
	lf.fd.Close()
}

func main() {
	var lf DataFile
	i := 0
	lf.Open()
	defer lf.Close()
	for {
		i++
		str1 := fmt.Sprintf("message: %02d\n", i)
		b := []byte(str1)
		lf.Write(b)
//		if i % 10 ==  7 {
//			lf.Close()
//			//lf.Open()
//		}
//		if i % 10 ==  9 {
//			//lf.Close()
//			lf.Open()
//		}
		time.Sleep(time.Second * 1)
	}
}



